package com.example.customview.recyclerview;

/**
 * 描述
 *
 * @创建时间 2023/10/8 21:44
 */

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * 添加分割线  10px的红色
 */
 class RecyclerItemDecoration extends RecyclerView.ItemDecoration {
    private Paint mPaint;

    public RecyclerItemDecoration() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
    }

    /**
     * 基本操作就是留出分割线位置
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 代表在每个底部的位置留出10px来绘制分割线 最后一个位置不需要分割线
        int position = parent.getChildAdapterPosition(view);

        Log.e("TAG", "position --> " + position + "  " + parent.getChildCount());
        // parent.getChildCount() 是不断变化的 现在没办法保证最后一条
        // 保证第一条
        // if(position != parent.getChildCount()-1){
        if (position != 0) {
            outRect.top = 10;
        }
    }

    /**
     * 绘制分割线
     */
    @Override
    public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
        // 利用canvas想绘制什么就绘制什么
        // 在每一个item的头部绘制
        int childCount = parent.getChildCount();

        // 指定绘制区域
        Rect rect = new Rect();
        rect.left = parent.getPaddingLeft();
        rect.right = parent.getWidth() - parent.getPaddingRight();
        for (int i = 1; i < childCount; i++) {
            // 分割线的底部是ItemView的头部
            rect.bottom = parent.getChildAt(i).getTop();
            rect.top = rect.bottom - 10;
            canvas.drawRect(rect, mPaint);
        }
    }
}